<template>
    <el-dialog :title="dialogFrom.dialogTitle" :model-value="dialogFrom.dialogVisible"
        @input:model-value="updateDialogVisible" align-center width="60%" :before-close="onCancel">
        <el-form ref="unifiedFormRef" :model="dataInfo" :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="上级菜单" prop="parentId">
                <el-select v-model="dataInfo.parentId" placeholder="请选择上级菜单">
                    <el-option label="主目录" :value="0"></el-option>
                    <el-option v-for="item in parentList" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="菜单名称" prop="name">
                <el-input v-model="dataInfo.name" placeholder="请填写菜单名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="菜单图标" prop="icon">
                <el-select v-model="dataInfo.icon" filterable placeholder="请选择菜单图标" clearable
                    popper-class="icon-select">
                    <el-option v-for="(item, index) in iconList" :key="index" :label="item.label" :value="item.label">
                        <div class="icon-item-li">
                            <component :is="item.label" style="width: 25px; height: 25px; color: #373737;" />
                        </div>
                    </el-option>
                    <template #label>
                        <div class="select-label">
                            <component :is="dataInfo.icon" style="width: 1em; height: 1em; margin-right: 8px" /> {{
                                dataInfo.icon }}
                        </div>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="显示排序" prop="sort">
                <el-input-number v-model="dataInfo.sort" clearable></el-input-number>
            </el-form-item>
            <el-form-item label="菜单类型" prop="menuType">
                <el-radio-group v-model="dataInfo.menuType">
                    <el-radio label="目录" :value="1"></el-radio>
                    <el-radio label="菜单" :value="2"></el-radio>
                    <el-radio label="按钮" :value="3"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否外链" prop="isFrame" v-if="dataInfo.menuType === 2">
                <el-radio-group v-model="dataInfo.isFrame">
                    <el-radio label="是" :value="1"></el-radio>
                    <el-radio label="否" :value="0"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="路由地址" prop="path" v-if="dataInfo.menuType === 2">
                <el-input v-model="dataInfo.path" placeholder="请填写路由地址" clearable></el-input>
            </el-form-item>
            <el-form-item label="路由参数" prop="query" v-if="dataInfo.menuType === 2">
                <el-input v-model="dataInfo.query" placeholder="请填写路由参数" clearable></el-input>
            </el-form-item>
            <el-form-item label="组件路径" prop="component" v-if="dataInfo.menuType === 2">
                <el-input v-model="dataInfo.component" placeholder="请填写组件路径" clearable></el-input>
            </el-form-item>
            <el-form-item label="权限标识" prop="perms" v-if="dataInfo.menuType && dataInfo.menuType !== 1">
                <el-input v-model="dataInfo.perms" placeholder="请填写权限标识" clearable></el-input>
            </el-form-item>
            <el-form-item label="是否显示" prop="visible">
                <el-radio-group v-model="dataInfo.visible">
                    <el-radio label="隐藏" :value="1"></el-radio>
                    <el-radio label="显示" :value="0"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="dataInfo.remark" placeholder="请填写备注" clearable type="textarea"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="onSubmit(unifiedFormRef)" :loading="loading">提交</el-button>
                <el-button @click="onCancel">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
// -------------------------------------------------导入相关引用-------------------------------------------------

import { ref, watch } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import type { DataInfo, TableData } from '@/api/system/SysMenu'
import { getList, getInfo, saveInfo, editInfo } from '@/api/system/SysMenu'

// -------------------------------------------------相关参数定义-------------------------------------------------
const loading = ref(false);

const props = withDefaults(defineProps<{
    dialogFrom: DialogFrom
}>(), {
    dialogFrom: () => ({
        dialogTitle: '',
        dialogVisible: false,
        infoId: null,
        parentId: 0
    })
});

const unifiedFormRef = ref<FormInstance | undefined>(undefined);

const rules: FormRules = {
    parentId: [
        { required: true, message: '上级菜单ID不能为空', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '菜单名称不能为空', trigger: 'blur' }
    ],
    menuType: [
        { required: true, message: '菜单类型不能为空', trigger: 'blur' }
    ],
    sort: [
        { required: true, message: '显示排序不能为空', trigger: 'blur' }
    ],
}

const initData = {
id: null,
    parentId: 0,
    name: '',
    path: '',
    component: '',
    sort: null,
    query: '',
    isFrame: 0,
    menuType: null,
    visible: 0,
    perms: '',
    icon: '',
    remark: '',
}

const dataInfo = ref<DataInfo>({
    ...initData
})

const parentList = ref<TableData[]>([])

const iconList = ref<any[]>([]);

// ---------------------------------------------------事件定义--------------------------------------------------

const emit = defineEmits(['update:dialogFrom', 'onParentSearch']);

// -------------------------------------------------操作方法定义-------------------------------------------------

/**
 * 监听dialogFrom参数
 */
watch(() => props.dialogFrom.dialogVisible, (newValue, oldValue) => {
    if (newValue) {
        getInfoApi();
        getListApi();
        iconList.value = []
        // [key, component]
        Object.entries(ElementPlusIconsVue).map((item) => {
            const [key, component] = item;
            iconList.value.push({
                label: key,
                component: component
            });
        });
    }
})

/**
 * 获取列表信息
 */
const getListApi = async () => {
    parentList.value = [];
    await getList({
        menuType: 1
    }).then((res) => {
        if (res.data.code === 200) {
            parentList.value.push(...res.data.data);
        }
    })
    await getList({
        menuType: 2
    }).then((res) => {
        if (res.data.code === 200) {
            parentList.value.push(...res.data.data);
        }
    })
}

/**
 * 获取表单信息
 */
const getInfoApi = async () => {
    const infoId = props.dialogFrom.infoId;
    if (infoId) {
        await getInfo(infoId).then((res) => {
            if (res.data.code === 200) {
                dataInfo.value = res.data.data;
            }
        })
    }else{
        dataInfo.value.parentId = props.dialogFrom.parentId;
    }
}

/**
 * 提交表单
 */
const onSubmit = async (ref: FormInstance | undefined) => {
    if (!ref) return
    loading.value = true;
    await ref.validate((valid, fields) => {
        if (valid) {
            if (props.dialogFrom.infoId) {
                editInfo(dataInfo.value).then((res) => {
                    loading.value = false;
                    if (res.data.code === 200) {
                        ElMessage.success({
                            message: '修改成功',
                            type: 'success'
                        })
                        onCancel();
                    }
                })
            } else {
                saveInfo(dataInfo.value).then((res) => {
                    loading.value = false;
                    if (res.data.code === 200) {
                        ElMessage.success({
                            message: '添加成功',
                            type: 'success'
                        })
                        onCancel();
                    }
                })
            }
        }else { 
            loading.value = false;
        }
    })
}

/**
 * 关闭弹窗
 */
const onCancel = () => {
    resetFrom();
    emit('update:dialogFrom', {
        dialogVisible: false,
        dialogTitle: '',
        infoId: null,
        parentId: 0
    });
    emit('onParentSearch');
}

/**
 * 重置表单
 */
const resetFrom = () => {
    dataInfo.value = { ...initData }
}

/**
 * 更新弹窗显示状态
 * @param dialogFromParams
 * @returns void
 */
const updateDialogVisible = (dialogFromParams: DialogFrom) => {
    emit('update:dialogFrom', dialogFromParams);
}

// -------------------------------------------------实体定义区-------------------------------------------------

/**
 * 弹窗信息
 */
export interface DialogFrom {
    dialogTitle: string;
    dialogVisible: boolean;
    infoId: number | null;
    parentId: number;
}
</script>

<style lang="scss" scoped>
.select-label {
    height: 100%;
    display: flex;
    align-items: center;
}
</style>

<style lang="scss">
.icon-select {
    width: calc(60% - 132px);

    .el-scrollbar .el-select-dropdown__wrap .el-scrollbar__view {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: flex-start;

        li {
            width: 50px;
            height: 50px;
            padding: 0;

            .icon-item-li {
                width: 40px;
                height: 40px;
                border-radius: 3px;
                border: 1px solid #bababa;
                display: flex;
                justify-content: center;
                align-items: center;
                margin: 5px;
            }
        }
    }
}
</style>